import 'package:flutter/material.dart';

class RefreshPage extends StatefulWidget {
  @override
  _RefreshPageState createState() => _RefreshPageState();
}

class _RefreshPageState extends State<RefreshPage> {
  List<String> ctiyList = [
    "上海1",
    "背景2",
    "西安3",
    "上海4",
    "背景5",
    "西安6",
    "上海7",
    "背景89",
    "西安9",
    "上海90",
    "背景11",
    "西安12",
    "西安9",
    "上海90",
    "背景11",
    "西安12"
  ];

  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('上啦加载下啦刷新'),
      ),
      body: Container(
        child: RefreshIndicator(
            child: ListView(
              controller: _scrollController,
              children: _buildList(),
            ),
            onRefresh: _handleRefresh),
      ),
    );
  }

  Future<Null> _handleRefresh() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      ctiyList = ctiyList.reversed.toList();
    });
    return null;
  }

  List<Widget> _buildList() {
    return ctiyList.map((city) => _item(city)).toList();
  }

  Widget _item(String city) {
    return Container(
      height: 50,
      margin: EdgeInsets.only(bottom: 5),
      decoration: BoxDecoration(color: Colors.teal),
      child: Center(
        child: Text(
          city,
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
      ),
    );
  }

  void _loadData() async {
    await Future.delayed(Duration(microseconds: 500));
    setState(() {
      List<String> list = List<String>.from(ctiyList);
      ctiyList.addAll(list);
    });
  }
}
